package com.farm.wcp.controller;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.farm.authority.domain.User;
import com.farm.authority.password.PasswordProviderService;
import com.farm.authority.service.UserServiceInter;
import com.farm.core.auth.domain.LoginUser;
import com.farm.core.page.ViewMode;
import com.farm.file.FarmFileServiceInter;
import com.farm.file.enums.FileModel;
import com.farm.parameter.FarmParameterService;
import com.farm.wcp.util.CheckCodeUtil;
import com.farm.wcp.util.ThemesUtil;
import com.farm.web.WebUtils;


@RequestMapping("/userspace")
@Controller
public class UserWebController extends WebUtils {
	private static final Logger log = Logger.getLogger(UserWebController.class);
	@Resource
	private UserServiceInter userServiceImpl;
	@Resource
	private FarmFileServiceInter farmFileServiceImpl;

	
	@RequestMapping("/PubRegist")
	public ModelAndView regist(HttpSession session, HttpServletRequest request) {
		initLoginSalt(session, request);
		CheckCodeUtil.setRequireCheckCode(session);
		return ViewMode.getInstance().putAttr("imgUrl", null)
				.returnModelAndView(ThemesUtil.getThemePath() + "/userspace/regist");
	}

	
	@RequestMapping("/PubRegistCommit")
	public ModelAndView registSubmit(String photoid, String loginname, String name, String password, String orgid,
			String checkcode, String email, HttpSession session, HttpServletRequest request) {
		try {
			CheckCodeUtil.setRequireCheckCode(session);
			if (FarmParameterService.getInstance().getParameter("config.show.local.regist.able ").equals("false")) {
				throw new RuntimeException("该操作已经被管理员禁用!");
			} // 是否启用登录验证码
			if (!CheckCodeUtil.isCheckCodeAble(name, checkcode, session)) {
				// throw new CheckCodeErrorException("验证码未通过");
				// 该方法会自动抛出异常
			}
			{// 校验用户登录名、邮箱
				if (userServiceImpl.validateIsRepeatLoginName(loginname, null)) {
					throw new RuntimeException("登录名已经存在" + loginname);
				}
			}
			User user = new User();
			{// 注册用户级别资料
				if (StringUtils.isNotBlank(photoid)) {
					user.setImgid(photoid);
				}
				user.setLoginname(loginname);
				user.setName(name);
				user.setState("1");
				user.setType("1");
				user = userServiceImpl.registUser(user, orgid);
				// wdapFileServiceImpl.submitFile(user.getImgid());
			}
			String clientOldPassword = PasswordProviderService.getInstanceProvider().getClientPassword(loginname,
					FarmParameterService.getInstance().getParameter("config.default.password"));
			// 设置用户密码
			userServiceImpl.editUserPasswordByLoginName(loginname, clientOldPassword, password);
			// 处理用户为待审核状态
			if (FarmParameterService.getInstance().getParameter("config.registed.audit").equals("true")) {
				user = userServiceImpl.editUserState(user.getId(), "3", user);
			}
			Map<String, String> links = new HashMap<String, String>();
			links.put("立即登陆系统", "login/PubLogin.html");
			return ViewMode.getInstance().putAttr("MESSAGE", "用户" + user.getLoginname() + "已经注册成功!")
					.putAttr("LINKS", links).returnModelAndView(ThemesUtil.getThemePath() + "/simple-message");
		} catch (Exception e) {
			log.error(e.getMessage());
			initLoginSalt(session, request);
			return ViewMode.getInstance().putAttr("photoid", photoid).putAttr("loginname", loginname)
					.putAttr("email", email).putAttr("name", name).putAttr("orgid", orgid)
					.putAttr("imgUrl", farmFileServiceImpl.getDownloadUrl(photoid, FileModel.IMG))
					.putAttr("errorMessage", e.getMessage())
					.returnModelAndView(ThemesUtil.getThemePath() + "/userspace/regist");
		}
	}

	
	@RequestMapping("/editCurrentUser")
	public ModelAndView editCurrentUser(String name, String photoid, String email, HttpSession session) {
		try {
			if (!FarmParameterService.getInstance().getParameterBoolean("config.useredit.reception.able")) {
				return ViewMode.getInstance().setError("禁止前台修改用户信息", new RuntimeException("禁止前台修改用户信息"))
						.returnModelAndView("web-simple/simple-500");
			}
			// 修改用户信息
			LoginUser currentUser = getCurrentUser(session);
			String oldimgid = userServiceImpl.getUserEntity(currentUser.getId()).getImgid();
			if (StringUtils.isNotBlank(oldimgid) && farmFileServiceImpl.getFileBase(oldimgid) != null) {
				farmFileServiceImpl.freeFile(oldimgid);
			}
			userServiceImpl.editCurrentUser(currentUser.getId(), name, photoid, null);
			if (StringUtils.isNotBlank(photoid)) {
				farmFileServiceImpl.submitFile(photoid);
			}
			session.setAttribute("USEROBJ", userServiceImpl.getUserEntity(currentUser.getId()));
			return ViewMode.getInstance().putAttr("OK", "OK").returnRedirectUrl("/userspace/settinginfo.do?OK=OK");
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnModelAndView("web-simple/simple-500");
		}

	}

	@RequestMapping("/editCurrentUserPwdCommit")
	public ModelAndView editCurrentUserPwdCommit(String password, String newPassword, String checkcode,
			HttpSession session, HttpServletRequest request) {
		try {
			// 启用登录验证码
			CheckCodeUtil.setRequireCheckCode(session);
			if (!CheckCodeUtil.isCheckCodeAble(getCurrentUser(session).getLoginname(), checkcode, session)) {
				throw new RuntimeException("验证码错误!");
			}
			// 如果验证失败会抛出异常
			userServiceImpl.editUserPassword(getCurrentUser(session).getId(), password, newPassword,
					getLoginSalt(session));
			return ViewMode.getInstance().putAttr("OK", "OK")
					.returnModelAndView("web-simple/userspace/user-setting-password");
		} catch (Exception e) {
			initLoginSalt(session, request);
			return ViewMode.getInstance().setError(e.getMessage(), e)
					.returnModelAndView("web-simple/userspace/user-setting-password");
		}
	}

	
	@RequestMapping("/settinginfo")
	public ModelAndView settinginfo(HttpServletRequest request, String OK, HttpSession session) {
		ViewMode view = ViewMode.getInstance();
		try {
			return view.putAttr("OK", OK).returnModelAndView("web-simple/userspace/user-setting-userinfo");
		} catch (Exception e) {
			return view.setError(e.getMessage(), e).returnModelAndView("web-simple/simple-500");
		}
	}

	
	@RequestMapping("/settingpsd")
	public ModelAndView settingpsd(HttpServletRequest request, HttpSession session) {
		ViewMode view = ViewMode.getInstance();
		try {
			CheckCodeUtil.setRequireCheckCode(session);
			initLoginSalt(session, request);
			return view.returnModelAndView("web-simple/userspace/user-setting-password");
		} catch (Exception e) {
			return view.setError(e.getMessage(), e).returnModelAndView("web-simple/simple-500");
		}
	}
}
